package com.hx.service.Impl;

import com.hx.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据用户id获取访问次数
     * @param userId
     * @return
     */
    @Override
    public synchronized int getUserCount(Integer userId) {

        int count = 0;
        String userCountKey = "userCount_"+userId;
        String userCountValue = (String) redisTemplate.opsForValue().get(userCountKey);
        log.info("用户{}正在访问秒杀接口，写入redis中。",userId);

        if(userCountValue == null){
            count = 0;
            log.info("用户{}访问初始化！",userId);
        }else{
            count = Integer.parseInt(userCountValue) + 1;
            log.info("用户{}进行第{}次访问!",userId,count);
        }
        redisTemplate.opsForValue().set(userCountKey,String.valueOf(count),30, TimeUnit.SECONDS);

        return count;
    }
}
